package com.controller.lyxmcontroller.controller.login;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.controller.lyxmcontroller.config.WebSecurityConfig;


@Controller
public class loginController {
	/*
	 	@GetMapping("/")
	    public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String account, Model model) {
	        model.addAttribute("name", account);
	        return "index";
	    }
*/
	    @GetMapping("/login")
	    public String login(String url,Model model) {
	    	if(""!=url){
	    		model.addAttribute("url",url);
	    	}else{
	    		model.addAttribute("url","");
	    	}
	    	return "/needlog/login";
	    }

	    @PostMapping("/loginPost")
	    public @ResponseBody Map<String, Object> loginPost(String account, String password, HttpSession session) {
	        Map<String, Object> map = new HashMap<>();
	        if(!"root".equals(account)){
	        	map.put("success", false);
        	    map.put("message", "账户错误（内部测试 固定账户）");
	        	 return map;
	        }
	   	 	if (!"123456".equals(password)) {
	            map.put("success", false);
	            map.put("message", "密码错误（内部测试 固定账户）");
	            return map;
	        }

	        // 设置session
	        session.setAttribute(WebSecurityConfig.SESSION_KEY, account);

	        map.put("success", true);
	        map.put("message", "登录成功");
	        return map;
	    }

	    @GetMapping("/logout")
	    public void logout(HttpSession session,HttpServletRequest req,HttpServletResponse res) {
	        // 移除session
	    	StringBuffer url = req.getRequestURL();
	    	System.out.println(url);
	        session.removeAttribute(WebSecurityConfig.SESSION_KEY);
	        try {
				res.sendRedirect("http://localhost:8002/index");
				System.out.println("aaaaaaaaaaaaaaaaa");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }

	
	
}
